package com.ingenio.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ingenio.business.Provincia;
import com.ingenio.dao.ProvinciaAdapter;

/**
 * Servlet implementation class ABMProvinciasServlet
 */
@WebServlet("/ABMProvincia")
public class ABMProvinciasServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ABMProvinciasServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String descripcion = "";
		ProvinciaAdapter pa = new ProvinciaAdapter();
		Provincia p = null;		
		
		if("delete".equals(request.getParameter("type"))){
			//FALTA QUE ELIMINE LAS LOCALIDADES DE ESA PROVINCIA!!
			try {
				Integer id = Integer.parseInt(request.getParameter("id"));
				p = pa.devolverProvincia(id);
				pa.eliminarProvincia(p);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("edit".equals(request.getParameter("type"))){
			if(request.getParameter("descripcion_provincia") != null && request.getParameter("id_provincia_hidden") != null){
				descripcion = request.getParameter("descripcion_provincia");
				Integer id = Integer.parseInt(request.getParameter("id_provincia_hidden"));
				try {
					p = pa.devolverProvincia(id);
					p.setDescProvincia(descripcion);
					pa.modificarProvincia(p);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if("add".equals(request.getParameter("type"))){
			if(request.getParameter("descripcion_provincia") != null){
				descripcion = request.getParameter("descripcion_provincia");
				try {
					p = new Provincia(null, descripcion, true);
					pa.agregarProvincia(p);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		response.sendRedirect("provincias/listado_provincia.jsp");
	}
}


